package com.yupi.yupicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 文件上传实现
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    protected void processFile(Object inputSource, File file)  throws  Exception{
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }

    @Override
    protected String getOrginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        String originalFilename = multipartFile.getOriginalFilename();
        return originalFilename;
    }

    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf( multipartFile==null, ErrorCode.PARAMS_ERROR,"上传图片不能为空");
        // 校验文件大小
        ThrowUtils.throwIf( multipartFile.getSize() > 1024 * 1024 * 2, ErrorCode.PARAMS_ERROR,"上传图片不能大于2M");
        // 校验文件后缀
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> fileSuffixList = Arrays.asList("jpg", "jpeg", "png", "wpeg");
        ThrowUtils.throwIf(!fileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR,"上传图片格式不正确");
    }
}
